package com.bsoft.gol.hcs.specialist.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.QueryMedicalSkillListReq;
import com.bsoft.gol.hcs.clinical.bean.vo.ConsultAskVo;
import com.bsoft.gol.hcs.clinical.bean.vo.DepartmentListVo;
import com.bsoft.gol.hcs.clinical.dao.ConsultAskDAO;
import com.bsoft.gol.hcs.clinical.entity.HoConsultAsk;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.common.bean.request.GetFusConsultIdRequest;
import com.bsoft.gol.hcs.common.bean.response.FusConsultResponse;
import com.bsoft.gol.hcs.common.dao.FusConsultAskDAO;
import com.bsoft.gol.hcs.common.entity.FusConsultAsk;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import hcn.util.BaseResponse;
import com.bsoft.gol.hcs.his.service.IMedicalSkillsHisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.bsoft.gol.hcs.specialist.dao.FusTeamChronicGroupRecordDAO;
import com.bsoft.gol.hcs.specialist.entity.FusTeamChronicGroupRecordEntity;
import com.bsoft.gol.hcs.specialist.service.ICommonService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import org.atag.util.http.KdHttpClientUtil;

import java.sql.Timestamp;
import java.util.List;

/**
 * @Description: 流调服务层
 * @Author: zhaorb
 * @Date: 2020/7/6 16:46
 **/
@SsdevService("specialistCommon")
public class CommonService implements ICommonService {
    private static final Logger logger = LoggerFactory.getLogger(CommonService.class);

    @Autowired
    FusConsultAskDAO fusConsultAskDAO;

    @Autowired
    ConsultAskDAO consultAskDAO;
    @Autowired
    private FusTeamChronicGroupRecordDAO fusTeamChronicGroupRecordDAO;
    @Autowired
    private IMedicalSkillsHisService medicalSkillsHisService;

    @Value("${project_source}")
    private String projectSource;


    @Override
    @RpcService
    public FusConsultResponse getFusConsultId(GetFusConsultIdRequest request) throws ControllerException {
        if (CommonUtils.isNull(request.getAge())) {
            List<FusTeamChronicGroupRecordEntity> records =
                    fusTeamChronicGroupRecordDAO.findFusRecordsByCardNumberOrPatientId(request.getIdCardType(),
                            request.getIdCardNo(), request.getPatientCode());
            if (CommonUtils.isNotEmpty(records)) {
                for (int i = 0; i < records.size(); i++) {
                    FusTeamChronicGroupRecordEntity entity = records.get(i);
                    if (CommonUtils.isNotNull(entity.getAge())) {
                        request.setAge(entity.getAge().longValue());
                    }
                }
            }
        }
        FusConsultAsk savefusConsultAskEntity = new FusConsultAsk();
        FusConsultResponse fusConsultResponse = new FusConsultResponse();
        QueryMedicalSkillListReq qasrequest = new QueryMedicalSkillListReq();
        List<DepartmentListVo> departmentListVos = null;
        FusConsultAsk fusConsultAskEntity = fusConsultAskDAO.getConsultInfoByDoctorId(request.getDoctorId(),
                request.getConsultMpiId());
        if (fusConsultAskEntity == null) {
            // return result.setResultError("成员不存在");
        } else {
            if (CommonUtils.isEmpty(fusConsultAskEntity.getFinishedTime())) {
                qasrequest.setBussType(request.getType());
                qasrequest.setConsultId(fusConsultAskEntity.getConsultId());

                ConsultAskVo vo = new ConsultAskVo();
                try {
                    if (Constants.HOL.equals(projectSource)) {
                        logger.info("进入互联网医院");
                        HoConsultAsk consultAsk = consultAskDAO.getConsultAskAll(qasrequest);
                        BeanUtils.copyProperties(consultAsk, vo);
                        vo.setConsultId(consultAsk.getConsultId() + "");
                    } else {
                        logger.info("进入智慧健康通");
                        vo = medicalSkillsHisService.getHcnConsultAsk(qasrequest).getData();
                    }
                    //查询到聊天结束，更新专科随访中的结束时间
                    if (CommonUtils.isNotEmpty(vo) && CommonUtils.isNotEmpty(vo.getFinishedTime())) {
                        fusConsultAskDAO.updateById(vo.getFinishedTime(),fusConsultAskEntity.getFusConsultAskId());
                    }else{//直接返回consultId
                        BaseResponse<FusConsultResponse> baseResp = new BaseResponse();
                        fusConsultResponse.setConsultId(fusConsultAskEntity.getConsultId()+"");
                        fusConsultResponse.setOrganizationId(fusConsultAskEntity.getOrgId());
                        return fusConsultResponse;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new ControllerException("获取问诊信息失败"+e.getMessage());
                }
            }
        }

        String str = null;
        try {
            String url ="";
            if (Constants.HOL.equals(projectSource)) {
                logger.info("进入互联网医院");
                //doctorListVos = sysParameterDAO.queryDoctorList(request);
                logger.info(System.getProperty("java.class.path") + "");
                url = Constants.HOL_FAMILY_URL + Constants.GET_FUS_CONSULT_ID;
            } else {
                logger.info("进入智慧健康通");
                logger.info(System.getProperty("java.class.path") + "");
                url = Constants.GOL_CLIENT_URL + Constants.GET_FUS_CONSULT_ID;
            }
            logger.info("url:{}", url);
            try {
                str = KdHttpClientUtil.doPost(url, JSONUtils.writeValueAsString(request), null);
            } catch (Exception e) {
                throw new ControllerException(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            }
        } catch (Exception e) {
            logger.error("getFusConsultId:Exception", e);
            throw new ControllerException(e.getMessage());
        }
        if (CommonUtils.isNotEmpty(str)) {
            JSONObject jsonObject = JSONObject.parseObject(str);
            logger.info("str:{}", str);
            logger.info("jsonObject:{}", jsonObject.toJSONString());
            try {
                if (CommonUtils.isNotEmpty(jsonObject)) {
                    JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    if (CommonUtils.isNotEmpty(jsonObject1)) {
                        fusConsultResponse = JSONObject.parseObject(jsonObject1.toString(),
                                FusConsultResponse.class);
                        return fusConsultResponse;
                    } else {
                        if (CommonUtils.isNotEmpty(jsonObject.getInteger("code"))) {
                            throw new ControllerException(jsonObject.getInteger("code"),
                                    jsonObject.getString("message"));
                        } else {
                            throw new ControllerException(jsonObject.getString("message"));
                        }
                    }
                } else {
                    throw new ControllerException(jsonObject.getString("message"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                throw new ControllerException(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            }
//                    logger.info("queryDoctorList:{}", result);
            // return result;
        }

        if (CommonUtils.isNotEmpty(fusConsultResponse)) {
            savefusConsultAskEntity.setConsultId(fusConsultResponse.getConsultId());
            savefusConsultAskEntity.setAge(request.getAge());
            savefusConsultAskEntity.setConsultMpiId(request.getConsultMpiId());
            savefusConsultAskEntity.setDoctorId(request.getDoctorId());
            savefusConsultAskEntity.setConsultType(request.getConsultType());
            savefusConsultAskEntity.setCreateUserId(request.getDoctorId());
            savefusConsultAskEntity.setDeptId(request.getDepartmentId());
            savefusConsultAskEntity.setOrgId(request.getOrganizationId());
            savefusConsultAskEntity.setGender(request.getGender());
            savefusConsultAskEntity.setPatientIdentityCardType(request.getIdCardType());
            savefusConsultAskEntity.setPatientIdentityCardNumber(request.getIdCardNo());
            savefusConsultAskEntity.setPatientMedicalCardNumber(request.getPatientMedicalCardNumber());
            savefusConsultAskEntity.setPatientMedicalCardType(request.getPatientMedicalCardType());
            savefusConsultAskEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
            fusConsultAskDAO.save(savefusConsultAskEntity);
            return fusConsultResponse;
        }

        return null;
    }


}

